public class BinarySearchTree {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        
        public TreeNode(int val) {
            this.val = val;
        }
    }
    
    public TreeNode root;
    
    //查找
    public boolean search(int val) {
        TreeNode cur = root;
        while (cur != null) {
            if (cur.val == val) {
                return true;
            } else if (cur.val < val) {
                cur = cur.right;
            } else {
                cur = cur.left;
            }
        }
        return false;
    }
    
    //插入
    public void insert(int val) {
        TreeNode newNode = new TreeNode(val);
        if (root == null) {
            root = newNode;
            return;
        }
        TreeNode cur = root;//记录插入节点
        TreeNode parent = null;//插入节点的父亲节点
        while (cur != null) {
            if (cur.val < val) {
                parent = cur;
                cur = cur.right;
            } else if (cur.val > val) {
                parent = cur;
                cur = cur.left;
            }else {//重复元素不予插入
                return;
            }
        }
        //判断在父亲节点的左边还是右边进行插入
        if (parent.val < val) {
            parent.right = newNode;
        } else {
            parent.left = newNode;
        }
    }
    
    //删除
    public void remove(int val) {
        TreeNode cur = root;
        TreeNode parent = null;
        //先找到要删除的节点的位置
        while (cur != null) {
            if (cur.val < val) {
                parent = cur;
                cur = cur.right;
            } else if (cur.val > val) {
                parent = cur;
                cur = cur.left;
            }else {
                //找到要删除的节点了
                removeNode(parent,cur);//调用函数删除节点
                return;
            }
        }
    }
    
    private void removeNode(TreeNode parent,TreeNode cur) {
        //对节点的状态进行分类
        if (cur.left == null) {//要删除节点左子树为空树
            if (cur == root) {
                root = cur.right;
            }else if (cur == parent.left) {
                parent.left = cur.right;
            }else {
                parent.right = cur.right;
            }
        }else if (cur.right == null) {//要删除节点右子树为空树
            if (cur == root) {
                root = cur.left;
            }else if (cur == parent.left) {
                parent.left = cur.left;
            }else {
                parent.right = cur.left;
            }
        }else {//要删除节点左右都不为空
            TreeNode temp = cur.right;//用来指向叶子节点
            TreeNode tempParent = cur;//用来指向叶子节点的父节点
            while (temp != null) {
                tempParent = temp;
                temp = temp.left;
            }//找到了要替换的节点
            cur.val = temp.val;
            //替换完成后就删除叶子节点
            if (tempParent.left == temp) {
                tempParent.left = temp.right;//删除叶子节点
            }else {
                tempParent.right = temp.right;//删除叶子节点
            }
        }
    
    }
}
